package com.matt.service.impl;

import com.dotflat.training.service.XETTokenService;
import com.matt.commons.dto.sso.AreaDTO;
import com.matt.domain.ChildrenExtendInfo;
import com.matt.domain.Classes;
import com.matt.domain.course.ChildrenCourse;
import com.matt.domain.course.ChildrenCourseChangeRecord;
import com.matt.domain.course.ChildrenCourseItem;
import com.matt.domain.statistics.StatNurseryCourseCount;
import com.matt.foundation.DO.NonProcessCourseItemDO;
import com.matt.foundation.constant.ChildrenConstant;
import com.matt.foundation.constant.ChildrenCourseConstant;
import com.matt.foundation.constant.CourseConstant;
import com.matt.foundation.utils.DateUtil;
import com.matt.foundation.utils.JsonValidateUtil;
import com.matt.repository.ChildrenExtendInfoRepository;
import com.matt.repository.ClassesRepository;
import com.matt.repository.base.ChildrenCheckRecordRepository;
import com.matt.repository.base.ClassesChildrenRepository;
import com.matt.repository.base.CoursePlanItemRepository;
import com.matt.repository.course.ChildrenCourseChangeRecordRepository;
import com.matt.repository.course.ChildrenCourseItemRepository;
import com.matt.repository.course.ChildrenCourseRepository;
import com.matt.repository.statistics.StatNurseryCountRepository;
import com.matt.repository.statistics.StatNurseryCourseCountRepository;
import com.matt.service.*;
import com.matt.service.remoteCall.SsoCallService;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * *******************************
 * Created by Ron.
 * form com.matt
 * on 2017/9/29
 * *******************************
 */
@Service
@Slf4j
public class SchedulerPlanServiceImpl implements SchedulerPlanService {

    @Autowired
    private ChildrenExtendInfoRepository childrenExtendInfoRepository;

    @Autowired
    private CoursePlanItemRepository coursePlanItemRepository;

    @Autowired
    private TeachOperationLogService teachOperationLogService;

    @Autowired
    private ChildrenCourseItemRepository childrenCourseItemRepository;

    @Autowired
    private ChildrenCourseRepository childrenCourseRepository;

    @Autowired
    private VideoCassetteRecorderService videoCassetteRecorderService;

    @Autowired
    private ChildrenCourseChangeRecordRepository childrenCourseChangeRecordRepository;

    @Autowired
    private NoticeMessageService noticeMessageService;

    @Autowired
    private CourseNurseryService courseNurseryService;

    @Autowired
    private CourseEarlyService courseEarlyService;

    @Autowired
    private StatNurseryCountService statNurseryCountService;

    @Autowired
    private StatNurseryCourseCountService statNurseryCourseCountService;

    @Autowired
    private StatNurseryCourseCountRepository statNurseryCourseCountRepository;

    @Autowired
    private StatNurseryCountRepository statNurseryCountRepository;

    @Autowired
    private ChildrenCheckRecordRepository childrenCheckRecordRepository;

    @Autowired
    private SsoCallService ssoCallService;

    @Autowired
    private ClassesRepository classesRepository;

    @Autowired
    private ClassesChildrenRepository classesChildrenRepository;

    @Autowired
    private NurseryInfoRecordService nurseryInfoRecordService;

    @Autowired
    private XETTokenService xetTokenService;

    @Override
    public void resetCheckStatus() {
        childrenExtendInfoRepository.updateCheckStatusAndHealthyStatusAndCheckTimeAndSickName(
                ChildrenConstant.CheckStatus.ABSENT.codeOf(),
                ChildrenConstant.HealthyStatus.HEALTHY.codeOf(),
                null,
                "");
    }

    /**
     * 早教所排课程，处理孩子消课
     */
    @Override
    public void processChildrenCourseNonJoin(Date date) {
        String yesterday = DateUtil.millisToDateTime(DateUtil.plusDaysToDate(date, -1L).getTime(), "yyyy-MM-dd");
        String begDate = DateUtil.millisToDateTime(DateUtil.getCurrentDayBeginAndEnd(yesterday).get("beg").getTime(), "yyyy-MM-dd");
        String endDate = DateUtil.millisToDateTime(DateUtil.getCurrentDayBeginAndEnd(yesterday).get("end").getTime(), "yyyy-MM-dd");
        List<NonProcessCourseItemDO> nonProcessList = coursePlanItemRepository.findByStatusAndCourseDate(ChildrenCourseConstant.ItemStatus.NON_USED.codeOf(), begDate, endDate);
        nonProcessList.forEach(o -> {
            teachOperationLogService.addSystemProcessCourseItemLog(o.getChildrenId(), o.getCourseName(), o.getAreaId());
            ChildrenCourseItem courseItem = childrenCourseItemRepository.getOne(o.getChildrenCourseItemId());
            courseItem.setStatus(ChildrenCourseConstant.ItemStatus.USED.codeOf());
            courseItem.setRemark("系统逾期处理");
            childrenCourseItemRepository.save(courseItem);
            //减去课程数据
            ChildrenCourse childrenCourse = childrenCourseRepository.getOne(courseItem.getChildrenCourseId());
            childrenCourse.setTotalCourseSize(childrenCourse.getTotalCourseSize() - 1);
            //上课
            childrenCourse.setOverCourseSize(childrenCourse.getOverCourseSize() + 1);
            childrenCourseRepository.save(childrenCourse);
            //减去sat剩余课时
            ChildrenExtendInfo extendInfo = childrenExtendInfoRepository.findByChildrenId(courseItem.getChildrenId());
            extendInfo.setEarlyLeftCourseNum(extendInfo.getEarlyLeftCourseNum() - 1);
            childrenExtendInfoRepository.save(extendInfo);

            ChildrenCourseChangeRecord changeRecord = ChildrenCourseChangeRecord.of(null, childrenCourse.getChildrenId(), "系统逾期处理", -1, extendInfo.getEarlyLeftCourseNum(), "系统");
            childrenCourseChangeRecordRepository.save(changeRecord);
        });
    }


    @Override
    public void checkVCRStatus() {
        videoCassetteRecorderService.refreshAll();
    }


    @Override
    public void refreshNoticeMessage() {
    	//保存园区尚未设置课程备课审核者消息
        noticeMessageService.generateCourseAuditor();
        //给没有备主题课程的老师发送信息
        noticeMessageService.generateThemeCoursePrepare();
        //给没有备早教课程的老师发送消息
        noticeMessageService.generateEarlyCoursePrepare();
    }

    @Override
    public void refreshLivePlanNoticeMessage(Date time) {
        if (!DateUtil.isWednesday(time))
            return;
        noticeMessageService.generateLivePlanPrepare();
    }

    @Override
    public void refreshNoticeOverDue(Date date) {
        noticeMessageService.overdueProcess(date);
    }

    @Override
    public void processCourseStatus(Date date) {
        courseNurseryService.systemProcessCourse(date);
    }

    @Override
    public void nurseryCountStat(Date time) {
        Date yesterday = new Date(DateUtil.plusDays(time.getTime(), -1L));
        //TODO: 这里需要修正
        List<AreaDTO> areaDTOList =  ssoCallService.getAllArea();
        for (AreaDTO area : areaDTOList) {
            Long nurseryCount = statNurseryCountRepository.countNurseryCountByArea(ChildrenConstant.NurseryStatus.HAS_COURSE.codeOf(), area.getId());
            Long limitCount = statNurseryCountRepository.countNurseryLimitByArea(area.getId(), CourseConstant.Category.NURSERY.codeOf());

            List<Classes> classesList = classesRepository.findByAreaId(area.getId());
            List<Map> mapList = Lists.newArrayList();
            for (Classes classes : classesList){
                Map map = new HashMap();
                map.put("limitCount", classes.getLimitNum());
                map.put("classesName", classes.getName());
                int childCount = classesChildrenRepository.findChildrenByClasses(classes.getId()).size();
                map.put("childCount", childCount);
                mapList.add(map);
            }
            statNurseryCountService.updateNurseryLimitCount(area.getId(), nurseryCount == null ? 0 : nurseryCount.intValue(), limitCount == null ? 0 : limitCount.intValue(), yesterday, JsonValidateUtil.toJson(mapList));
        }

    }

    @Override
    public void nurseryCourseCountStat(Date time) {
        Date yesterday = new Date(DateUtil.plusDays(time.getTime(), -1L));
        String yesterdayStr = DateUtil.millisToDateTime(yesterday.getTime(), "yyyy-MM-dd");
        String begDate = DateUtil.millisToDateTime(DateUtil.getCurrentDayBeginAndEnd(yesterdayStr).get("beg").getTime(), "yyyy-MM-dd HH:mm:ss");
        String endDate = DateUtil.millisToDateTime(DateUtil.getCurrentDayBeginAndEnd(yesterdayStr).get("end").getTime(), "yyyy-MM-dd HH:mm:ss");

        //TODO: 这里需要修正
        List<AreaDTO> areaDTOList =  ssoCallService.getAllArea();
        List<StatNurseryCourseCount> statNurseryCountList = Lists.newArrayList();
        for (AreaDTO area : areaDTOList) {
            Integer clienteleCount = childrenCheckRecordRepository.findClienteleCountByDateAndAreaId(begDate, endDate, area.getId());
            Integer teacherCount = childrenCheckRecordRepository.findTeacherCountByDateAndAreaId(begDate, endDate, area.getId());
            statNurseryCourseCountService.updateTeacherClienteleCount(area.getId(), teacherCount, clienteleCount, yesterday);
        }
        statNurseryCourseCountRepository.saveAll(statNurseryCountList);
    }

    @Override
    public void getWorkDate() {
        nurseryInfoRecordService.getWorkDate();
    }

    @Override
    public void updateXetAccessToken(){
        xetTokenService.updateAccessToken();
    }
}
